<template>
    <module-view>
        <module-content>
            <el-button class="upload-btn" @click="onUpload({ multiple: true })" v-show="isShowUpload"><i class="iconfont icon-a-icon-Uploadthetemplate"></i> 上传附件</el-button>
            <oss-upload ref="ossUpload" :limit-params="newLimitParams" :module-type="moduleType" :limit="limit" @handle-success="handleSuccess"></oss-upload>

            <!-- 上传列表 -->
            <upload-manager @handle-remove="handleRemove" :type="type" />
        </module-content>
    </module-view>
</template>

<script>
import OssUpload from './oss-upload';
import UploadManager from '@/components/upload-file/src/upload-manager';
// import { moduleView, moduleContent } from '@/components/common-module';
import { getAnnexQuery } from './api/oss';

export default {
    components: { OssUpload, UploadManager },
    props: {
        //1.图片（bmp，jpg，png，gif，svg）单张图片大小不超过2M，单个单据最多可上传１０张图片
        //2.文件 （txt，docx，doc，xlsx，xls，ppt，pptx，）单个文件大小不超过20M，单个单据最多可上传１０个文件;pdf，zip，dwg 单个文件大小不超过100M，单个单据或表单最多可上传10个文件
        //3.视频 （mkv、mp4、avi、mov、wmv）单个视频大小不超过100M，单个单据最多可上传３个视频
        limitParams: {
            type: Object,
            default: () => {}
        },
        fileList: {
            //详情列表
            type: Array,
            default: () => []
        },
        fileIds: {
            //详情id列表
            type: Array,
            default: () => []
        },
        moduleType: {
            type: String,
            default: 'pms' //所属模块 可用值:cms,crm,fms,hrs,pms,scs,tss
        },
        isShowUpload: {
            type: Boolean,
            default: true //是否展示上传按钮
        },
        type: {
            type: String,
            default: '' //详情页列表才展示上传人  view
        }
    },
    data() {
        return {
            current: null, //getUserRootDoc 调接口赋值
            loading: false,
            defaultLimitParams: {
                //默认限制
                image: {
                    maxNum: 10,
                    type: 'bmp,jpg,png,gif,svg', //image/*
                    maxSize: 2 //2M
                },
                file: [
                    {
                        maxNum: 10,
                        type: 'txt,docx,doc,xlsx,xls,ppt,pptx',
                        maxSize: 20
                    },
                    {
                        maxNum: 10,
                        type: 'pdf,zip,dwg',
                        maxSize: 100
                    }
                ],
                video: {
                    maxNum: 3,
                    type: 'mkv,mp4,avi,mov,wmv',
                    maxSize: 100
                }
            },
            limit: 6 //单次批量上传最多6个
        };
    },
    computed: {
        // 增加当前文件数量 currentNum
        newLimitParams: {
            get() {
                let data = this.limitParams === undefined || Object.keys(this.limitParams)?.length === 0 ? this.defaultLimitParams : this.limitParams;
                Object.keys(data).forEach((key) => {
                    if (Array.isArray(data[key])) {
                        data[key].forEach((val) => {
                            val.currentNum = 0;
                        });
                    } else {
                        data[key].currentNum = 0;
                    }
                });
                return data;
            },
            set(val) {}
        }
    },
    methods: {
        /* 调用上传 */
        onUpload(params) {
            this.$refs.ossUpload.open(params, this.current);
        },

        /* 上传成功 */
        handleSuccess(res, fileTypeData) {
            // 处理currentNum数量
            if (Array.isArray(this.newLimitParams[fileTypeData.key])) {
                this.newLimitParams[fileTypeData.key].forEach((val) => {
                    val.type === fileTypeData.type && (val.currentNum += 1);
                });
            } else {
                this.newLimitParams[fileTypeData.key].currentNum += 1;
            }
            const fileList = this.handleOssData();
            this.$emit('on-success', res, fileList[0], fileList);
        },

        /* 移除 */
        handleRemove() {
            const fileList = this.handleOssData();
            this.$emit('on-remove', fileList[0], fileList);
        },

        /* 获取详情附件列表 传多个id 组件请求详情 */
        async getFileList(ids) {
            let res = await getAnnexQuery(ids);
            if (res?.data) {
                this.$oss.queue = res.data;
                this.$emit('on-success', {}, {}, res.data);
            }
        },

        /* 处理数据 oss.queue */
        handleOssData() {
            return this.$oss.queue?.map((val) => {
                let params = {};
                if ('annexId' in val) {
                    params = val;
                } else {
                    const res = val.resp?.data?.response;
                    if (res?.annex) {
                        const { documentName, fileSize, annexId, addName, addTime, urlAddress } = res?.annex;
                        params = {
                            documentName,
                            fileSize,
                            url: res.url,
                            annexId: annexId,
                            addName: addName,
                            addTime: addTime,
                            urlAddress
                        };
                    }
                }
                return params;
            });
        }
    },
    watch: {
        fileIds: {
            handler(val) {
                if (val.length) {
                    this.$oss.visible = true;
                    this.getFileList(val);
                } else {
                    this.$oss.queue = [];
                }
            },
            immediate: true,
            deep: true
        }
    }
};
</script>

<style lang="scss" scoped>
.upload-btn {
    margin-bottom: 8px;
    cursor: pointer;
    border-radius: 2px;
    padding: 8px 15px;
    color: #56585c;
    border: 1px solid #dcdfe6;
    &:hover {
        background: #f2f3f5;
    }
    i {
        color: #4e5969;
        font-size: 14px;
    }
}
</style>
